package com.zdp.strategy.handler;

import com.zdp.common.enums.ChannelType;
import com.zdp.strategy.entity.ChannelReq;
import com.zdp.strategy.entity.ExecuteBaseContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Objects;

@Slf4j
@RequiredArgsConstructor
public abstract class AbstractService<P extends ChannelReq, R> {

    private final List<AbstractChannelStrategy<P, R>> strategyList;

    public final R execute(ExecuteBaseContext<P> param) {
        Long mchId = param.getMchId();
        log.info("查询商户:{}开通的服务", mchId);

        return doExecute(param);
    }

    protected R doExecute(ExecuteBaseContext<P> param) {
        P p = param.getParam();
        ChannelType channelType = p.getChannelType();
        AbstractChannelStrategy<P, R> strategy = this.getAbstractChannelStrategy(strategyList, channelType);
        if (Objects.nonNull(param.getMock())) {
            if (param.getMock()) {
                strategy.mock();
            } else {
                log.error("服务:{} 渠道:{}");
                throw new RuntimeException("服务调用异常");
            }
        }
        return strategy.invoke(p);
    }

    protected abstract AbstractChannelStrategy<P, R> getAbstractChannelStrategy(List<AbstractChannelStrategy<P, R>> strategyList, ChannelType channelType);

}
